<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>iframe+postMessage跨域通信 子页面</title>
    <style>
        a{display: none;}
    </style>
</head>
<body>
<h2>子页面</h2>
<div>
    <h3>接收消息区域</h3>
    <span id="message"></span>

    <p>
        <a href="https://blog.csdn.net/tang_yi_/article/details/79401280">
            https://blog.csdn.net/tang_yi_/article/details/79401280
        </a>
    </p>
    <div>
        <input type="text" id="msg"><button type="button" onclick="sendMessage()">子说：</button>
    </div>
</div>
</body>
<script>
    window.addEventListener('message',function(event){
        if(window.parent !== event.source){return}
        console.log(event);
        document.getElementById('message').innerHTML = "收到"
            + event.origin + "消息：" + event.data;
        top.postMessage("子页面消息收到", 'http://127.0.0.1:3000/parent.html')
    }, false);

    function sendMessage() {
        var str=document.getElementById('msg').value;
        console.log(str);
        top.postMessage(str, "http://127.0.0.1:3000/parent.html");
    }
</script>
</html>
